﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace JsCompressorForYUICompressor
{
    public partial class Frm_Main : Form
    {
        /// <summary>
        /// 需要处理的文件列表
        /// </summary>
        private List<String> aFiles = new List<String>();
        /// <summary>
        /// 处理后的文件列表，如果要合并就会先保存这个列表
        /// </summary>
        private Dictionary<String, String> aNewFiles = new Dictionary<String, String>();
        /// <summary>
        /// 需要合并的文件
        /// </summary>
        private List<String> aMergeFiles = new List<String>();
        /// <summary>
        /// 文件输出路径
        /// </summary>
        private String aFilePath_Out = "";

        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_GetPaht_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "请选择输入文件夹：";
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txt_Path.Text = folderBrowserDialog1.SelectedPath;
                LoadFiles(txt_Path.Text);
            }
        }

        private void LoadFiles(String Path)
        {
            if (Directory.Exists(Path) == false)
            {
                txt_FileList.Text = "指定路径不存在！";
                return;
            }

            aFiles.Clear();
            String[] iFilePaths;
            if ((comB_FileType.SelectedIndex == 0) || (comB_FileType.SelectedIndex == 1))
            {
                iFilePaths = Directory.GetFiles(Path, "*.js", SearchOption.AllDirectories);
                aFiles.AddRange(iFilePaths);
            }
            if ((comB_FileType.SelectedIndex == 0) || (comB_FileType.SelectedIndex == 2))
            {
                iFilePaths = Directory.GetFiles(Path, "*.css", SearchOption.AllDirectories);
                aFiles.AddRange(iFilePaths);
            }
            if (aFiles.Count <= 0)
            {
                txt_FileList.Text = "指定路径下没有需要处理的文件！";
                return;
            }
            if (checkB_Merge.Checked)
            {
                aMergeFiles.AddRange(aFiles);
            }
            txt_FileList.Text = "";
            for (Int32 i = 0; i < aFiles.Count; i++)
            {
                txt_FileList.Text += aFiles[i] + Environment.NewLine;
            }
            tssLab_FileSum.Text = "文件总数：" + aFiles.Count.ToString();
        }

        private void Frm_Main_Load(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + @"\yuicompressor-2.4.6.jar") == false)
            {
                MessageBox.Show("没有找到yuicompressor-2.4.6.jar文件！", "提示");
                btn_GetPaht_In.Enabled = false;
                txt_Path.Enabled = false;
            }

            comB_charset.SelectedIndex = 0;
            comB_FileType.SelectedIndex = 0;
        }

        private void btn_GoOn_Click(object sender, EventArgs e)
        {
            if (aFiles.Count <= 0)
            {
                txt_RetList.Text = "没有需要处理的文件！";
                return;
            }

            this.Enabled = false;
            this.lab_Msg.Visible = true;
            Application.DoEvents();
            String iYuicPath = Application.StartupPath + @"\yuicompressor-2.4.6.jar";
            txt_RetList.Text = "";
            aNewFiles.Clear();
            for (Int32 i = 0; i < aFiles.Count; i++)
            {
                RunCMD(aFiles[i], iYuicPath);
                txt_RetList.Focus();
                txt_RetList.SelectionStart = txt_RetList.Text.Length - 1;
                txt_RetList.SelectionLength = 1;
                txt_RetList.ScrollToCaret();
                Application.DoEvents();
            }
            if (checkB_Merge.Checked)
            {
                //合并文件未做
            }
            this.Enabled = true;
            this.lab_Msg.Visible = false;
            MessageBox.Show("处理完成！", "提示");
        }

        private void btn_GetPaht_Out_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "请选择输出文件夹：";
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txt_PahtOut.Text = folderBrowserDialog1.SelectedPath;
                aFilePath_Out = txt_PahtOut.Text;
            }
        }

        private void RunCMD(String File, String YuicPath)
        {
            Process iPrcess = new Process();
            iPrcess.StartInfo.FileName = "cmd.exe";
            iPrcess.StartInfo.UseShellExecute = false;
            iPrcess.StartInfo.CreateNoWindow = true;
            iPrcess.StartInfo.RedirectStandardInput = true;
            iPrcess.StartInfo.RedirectStandardOutput = true;
            iPrcess.StartInfo.RedirectStandardError = true;
            iPrcess.Start();

            String iFileEx = Path.GetExtension(File);
            String iOutPath = aFilePath_Out;
            if (aFilePath_Out == "")
            {
                iOutPath = Path.GetDirectoryName(File);
            }
            if (checkB_OldPath.Checked)
            {
                iOutPath = Path.GetDirectoryName(File);
            }
            String iOutFilePath = iOutPath + @"\"
                + Path.GetFileNameWithoutExtension(File) + (checkB_Rename.Checked ? "_min" : "") + Path.GetExtension(File);

            String iOtherOper = "";
            if (iFileEx == ".js")
            {
                if (checkB_Nomunge.Checked == false)
                {
                    iOtherOper += " --nomunge ";
                }
                if (checkB_preserve_semi.Checked == false)
                {
                    iOtherOper += " --preserve-semi ";
                }
                if (checkB_disable_optimizations.Checked == false)
                {
                    iOtherOper += " --disable-optimizations ";
                }
            }

            iOtherOper += " --charset " + comB_charset.Text;

            String iCmdStr = String.Format("java -jar {0} -o {1} {2} {3}", YuicPath, iOutFilePath, iOtherOper, File);
            iPrcess.StandardInput.WriteLine(iCmdStr);
            iPrcess.StandardInput.WriteLine("exit");
            Debug.WriteLine(iCmdStr);

            StreamReader iReaderOutPut = iPrcess.StandardError;
            txt_RetList.Text += "开始处理 " + File + Environment.NewLine;
            while (!iReaderOutPut.EndOfStream)
            {
                txt_RetList.Text += iReaderOutPut.ReadLine() + Environment.NewLine;
            }
            txt_RetList.Text += File + " 处理完成！" + Environment.NewLine;
            txt_RetList.Text += Environment.NewLine;
            if (checkB_Merge.Checked)
            {
                aNewFiles.Add(Path.GetFileName(File), iOutFilePath);
            }
            iPrcess.WaitForExit();
            iPrcess.Close();
            iPrcess.Dispose();
            iReaderOutPut.Close();
            iReaderOutPut.Dispose();
            iPrcess = null;
            iReaderOutPut = null;
        }

        private void checkB_Merge_CheckedChanged(object sender, EventArgs e)
        {
            btn_Merges.Enabled = checkB_Merge.Checked;
            if (checkB_Merge.Checked)
            {
                aMergeFiles.Clear();
                aMergeFiles.AddRange(aFiles);
            }
        }

        private void btn_Merges_Click(object sender, EventArgs e)
        {
            using (Frm_MergeFiles iFrm_MFiles = new Frm_MergeFiles(aMergeFiles))
            {
                if (iFrm_MFiles.ShowDialog() == DialogResult.OK)
                {
                    String[] iMFiles = iFrm_MFiles.txt_Files.Text.Split(new Char[] { ',' });
                    aMergeFiles.Clear();
                    aMergeFiles.AddRange(iMFiles);
                }
            }
        }
    }
}
